package com.hxrk.jni;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;

import com.hxrk.cecardvr.CamParameter;
import com.hxrk.cecardvr.CamService;
import com.hxrk.cecardvr.LogUtils;
import com.hxrk.cecardvr.MyApplication;
import com.hxrk.cecardvr.Utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Mp4v2Native {

    private static Mp4v2Native mp4v2n = null;

    public static Mp4v2Native getInstance() {
        if (mp4v2n == null)
            mp4v2n = new Mp4v2Native();
        return mp4v2n;
    }

    public void transImage(String fromFile, String toFile, int width, int height, int quality) {
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(fromFile);
            int bitmapWidth = bitmap.getWidth();
            int bitmapHeight = bitmap.getHeight();
            if (width == bitmapWidth && height == bitmapHeight)
                return;

            // 缩放图片的尺寸
            float scaleWidth = (float) width / bitmapWidth;
            float scaleHeight = (float) height / bitmapHeight;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            // 产生缩放后的Bitmap对象
            Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
            // save file
            File myCaptureFile = new File(toFile);
            FileOutputStream out = new FileOutputStream(myCaptureFile);
            if(resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)){
                out.flush();
                out.close();
            }
            if(!bitmap.isRecycled()){
                bitmap.recycle();//记得释放资源，否则会内存溢出
            }
            if(!resizeBitmap.isRecycled()){
                resizeBitmap.recycle();
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }

    public static Object hcsyn = new Object();
    /**
     * 保存图片回调
     * @param id
     * @param workid
     * @param filename
     */
    public void jpegcallback(String filename, int id, int workid, int ret)  {
        try {
            LogUtils.e("jpegcallback1", "拍照成功");

            Bundle mBundle = MyApplication.photoBundles.get(workid);
            if (mBundle != null) {
                if (ret == 0) {
                    int ChannclID = mBundle.getInt("ChannclID", 0);
                    int width = mBundle.getInt("width", -1);
                    int height = mBundle.getInt("height", -1);
                    //合成图片
                    if (ChannclID == 12) {
                        synchronized (hcsyn) {
                            String FilePath1 =  mBundle.getString("FilePath1");
                            if (FilePath1 == null) {
                                mBundle.putString("FilePath1", filename);
                                return;
                            } else {
                                if (width > 0 && height > 0) {
                                    transImage(FilePath1, FilePath1, width, height, 80);
                                    transImage(filename, filename, width, height, 80);
                                }

                                Bitmap bitmap1 = BitmapFactory.decodeFile(FilePath1);
                                int w1 = bitmap1.getWidth();
                                int h1 = bitmap1.getHeight();
                                Bitmap bitmap2  = BitmapFactory.decodeFile(filename);
                                int w2 = bitmap2.getWidth();
                                int h2 = bitmap2.getHeight();
                                Bitmap bitmap12 = Bitmap.createBitmap(w1 + w2, h1 > h2 ? h1 : h2, Bitmap.Config.ARGB_8888);
                                int w12 = bitmap12.getWidth();
                                int h12 = bitmap12.getHeight();
                                Canvas cv = new Canvas(bitmap12);
                                Rect rectsrc = new Rect();
                                rectsrc.set(0, 0, w1, h1);
                                Rect rectdst = new Rect();
                                rectdst.set(0, (h12 - h1) / 2, w1, h1);
                                cv.drawBitmap(bitmap1, 0, (h12 - h1) / 2, null);
                                cv.drawBitmap(bitmap2, w1, (h12 - h2) / 2, null);

                                File myCaptureFile = new File(mBundle.getString("FilePath"));
                                FileOutputStream out = new FileOutputStream(myCaptureFile);
                                if(bitmap12.compress(Bitmap.CompressFormat.JPEG, 80, out)){
                                    out.flush();
                                    out.close();
                                }

                                if(!bitmap1.isRecycled()){
                                    bitmap1.recycle();//记得释放资源，否则会内存溢出
                                }

                                if(!bitmap2.isRecycled()){
                                    bitmap2.recycle();//记得释放资源，否则会内存溢出
                                }

                                if(!bitmap12.isRecycled()){
                                    bitmap12.recycle();//记得释放资源，否则会内存溢出
                                }
                            }
                        }
                    } else {
                        if (width > 0 && height > 0) {
//                     Bitmap bitmap = BitmapFactory.decodeFile(filename).copy(Bitmap.Config.ARGB_8888, true);
//                    Canvas cv = new Canvas(bitmap);
//                    String dtext  = String.format("通道%02d    %s    %s", id + 1, Utils.putTextCPHM, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
//                    Paint paint = new Paint();
//                    paint.setTextSize(30);//设置字体大小
//                    paint.setColor(Color.RED);
//                    cv.drawText(dtext, 20, 50, paint);

                            transImage(filename, filename, width, height, 80);
                        }
                    }

                    mBundle.putInt("Result", 0);
                    MyApplication.mDvrManager.mDvrCallBack.doPhoto(mBundle);
                    // 保存多媒体信息在数据库
//                    MyApplication.mDvrManager.mDvrCallBack.AddMediaEx(mBundle);
                }else {
                    mBundle.putInt("Result", 1);
                    MyApplication.mDvrManager.mDvrCallBack.doPhoto(mBundle);
                }
                MyApplication.photoBundles.remove(workid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * video打开回调
     * @param devname  设备名
     * @param id    id
     * @param w 宽
     * @param h 高
     * @param c 编码
     */
    public void videocallback(String devname, int id, int w, int h, int c)  {
        LogUtils.e("Mp4v2Native", devname + "  id:" +id+"   width:"+w+"   height:"+h+"  code:"+c);
        if (id >= 0 && id < 4) {
            CamService.camParameters[id].initBmp(w,h,c,90000, 25, 16000, 1024, CamParameter.DEV_TYPE_USB);
        }
    }

    /**
     * video打开回调
     * @param devname  设备名
     * @param id    id
     * @param w 宽
     * @param h 高
     * @param c 编码
     */
    public void videocallback2(String devname, String c, String card, int id, int w, int h, int numerator, int denominator, int deviceVersion)  {
        try {
            if (!TextUtils.isEmpty(devname) && !TextUtils.isEmpty(c)){
                CamService.isRebootERR = false;
                MyApplication.editor.putBoolean("IS_REBOOT_ERR", false);
                MyApplication.editor.commit();

                String version = String.format("%d.%d.%d", (deviceVersion >> 16)&0xFF, (deviceVersion >> 8)&0xFF, deviceVersion &0xFF);
                LogUtils.e(devname + "  id:" +id+"   width:"+w+"   height:"+h+"  codex:"+c + "  card:"+card +"  numerator:"+numerator+"  denominator:"+denominator + "  deviceVersion:" + version);
                Utils.deviceVersion = version;
                Utils.cardName = card;

                // RD11-2_0_Car   USB Camera
                if (!Utils.cardName.contains("RD11-2_0_Car")){
                    CamService.IsWatermarkexDate = true;
                }else
                    CamService.IsWatermarkexDate = false;

                if (id >= 0 && id < 4) {
                    int ic = 0;
                    if (c.equals("H264"))
                        ic = CamParameter.FMT_TYPE_MJPEG;   //对调 过检使用 注意！！！！！！！！！！
                    else if (c.equals("MJPG"))
                        ic = CamParameter.FMT_TYPE_H264; //对调 过检使用 注意！！！！！！！！！！
                    else if (c.equals("YUYV"))
                        ic = CamParameter.FMT_TYPE_YUV422;
                    CamService.camParameters[id].initBmp(w,h,ic,90000, denominator/ numerator, 16000, 1024, CamParameter.DEV_TYPE_USB);
                    LogUtils.d(" open usb initbmp");
                }
            }else {
                // 摄像头打开异常，重启设备
                //LogUtils.d("usb open video error");
                CamService.closeVideo();

                /*if (!CamService.isRebootERR){
                    MyApplication.editor.putBoolean("IS_REBOOT_ERR", true);
                    MyApplication.editor.commit();
                    Utils.execCommand("reboot");
                }*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * USB原始地址数据地址返回回调
     * @param id id
     * @param p 地址
     * @param l 长度
     */
    public void videocallback3(int id, long p, int l) {
        CamService.camParameters[id].updateData(p, l);
        //LogUtils.e("Mp4v2Native", "  id:" +id+"   p:"+p+"   l :"+l);
    }

    /**
     * RGB数据地址返回回调
     * @param id id
     * @param p 地址
     */
    public void videocallbackface(int id, long p) {
        CamService.camParameters[id].updateRGBData(p);
//        LogUtils.e("Mp4v2Native", "videocallbackface    " + p);
    }

    /**
     * BGR 数据地址返回回调用于人脸识别
     * @param id id
     * @param p 地址
     * @param w 宽
     * @param h 高
     * @param len 长度
     */
    public void videocallbackface2(int id, long p, int w, int h, int len) {
//        LogUtils.e("Mp4v2Native videocallbackface2    id = " + id + "   p = " + p + "   w = " + w + "   h = " + h + "   len = " + len);
//        //BGR发送到人脸识别库处理成Mat
//        //Mat在转换成Bitmap绘制
//        CamService.camParameters[id].updateBGRData(id, p, w, h, len);
    }

    public void mipi264callback(int id, long p, int l) {
        LogUtils.e("Mp4v2Native", "mipi264callback    " + p);
    }

    public native long getmipiproc();
    public native long mp4init(int id, String title, int w, int h, int timeScale, int frameRate, int A_timeScale, int A_sampleDuration, int debug);
    public native void mipiSendH264Data(int id,  byte[] data, int size, int Frametype, int streamtype);
    public native int mp4packVideo(int id, long pdata, int size);
    public native int mp4packVideo2(int id, byte[] data, int size);
    public native int mp4packVideo2sub(int id, byte[] data, int size);
    public native int mp4packAudio(int id, long pdata, int size);
    public native int mp4packAudio2(int id, byte[] data, int size);
    public native int mp4close(int id);
    public native int RTPstart(int id, String ip, int port, int udpport, int datatype, int streamtype, int nettype, int PTType, int maxpk, byte[] Cmd1209,int is1078);
    public native int RTPctrl(int id, int KZZL, int YSPLX, int MLLX);
    public native int RTPfilestart(int id, String ip, int port, int udpport, int datatype, int KJKT, int streamtype, int nettype, int maxpk, int PTType, String files, byte[] cmd1209,int is1078);
    public native int RTPfilectrl(int id, int CSKZ, int KJKT_BS, String TDHFWZ);
    public native int jpeginit(int id, int w, int h);
    public native int jpegsave(int id, int workid, String filename);
    public native int jpegclose(int id);
    public native int GetMp4v2Version();
    public native int videoopen(int w, int h);
    public native int videoread(int id, Bitmap bitmap1, byte[] yuvdata, byte[] subyuvdata, boolean[] rtpstatus);
    public native int videowatermark(int id, int group, String info);
    public native int videoclose(int id);
    public native int videowatermarkex(int id, int index, String params, int x, int y, int s);

    // 设置传入图像函数指针
    public native void setNativeDrawFrame(long pf);

    // 设置传入图像函数指针
    public native void setNativeGetFaceNumber(long pf);

    public native void setParams(int cameraid, int channelnum, int sim_1,int sim_2,
                                 int sim_3,int sim_4,int sim_5,int sim_6);

    // 开始识别
    public native void faceStart(int status, int bFlag);

    static{
        System.loadLibrary("jnimp4v2");
    }
}
